"use client"
import styles from "./index.module.scss"
import { useForm } from "react-hook-form";
import FormItem from "@/components/formItem";
import React , { useState, useEffect } from "react" ;
import Image from "next/image"
import {loginServer} from '@/api'
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { setLocalStorage } from '@/utils/localStorage'
import { useStore } from '@/store';


interface LoginProps{
  className?: string
  title: string
  onlySubmit?: boolean
  onClose: () => void
  onOk: (data: any) => void
}


const Login : React.FC<LoginProps> = ({className = "", title = "", onClose, onOk, onlySubmit = false}) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
    control
  } = useForm();


const setUserInfo = useStore((state:any) => state.setUserInfo);
const setAccessToken = useStore((state:any) => state.setAccessToken);


  const rand = () => Math.ceil(Math.random() * 1000) * 5;

  const [captchSvg, setCaptchSvg] = useState<React.ReactSVGElement |  string>('');
  const [refreshSvg, setRefreshSvg ] = useState<number>(rand())
  const newChangeCaptch = () => setRefreshSvg(rand());



  const onSubmit = handleSubmit(async (formData) => {
    try {
      console.log('formData', formData);
      const {userName, password, captch} = formData
      if(actionName === "login"){ // 当前用户准备去登录
        const hasUser = await loginServer.findUserByuserName({username: userName});
        if(hasUser.code === 200){ // 有此用户，可以去登录了
          const {code, data, message} = await loginServer.login({username: userName, password, captcha: captch, actionType:actionName});
            if(code === 200){
              const {access_token, userId} = data;
               setAccessToken(access_token);
               setLocalStorage('access_token', access_token);
               toast.success("登录成功");
               const userInfo = await loginServer.finduserById({id: userId});
               if(userInfo.code === 200){
                  setUserInfo(userInfo.data)
                  setLocalStorage('userInfo', JSON.stringify(userInfo.data));
               };
               setTimeout(() => onClose(), 1000)
              //  onClose();
                onOk(formData)
            }else {
              toast.warn(message);
            }
        } else { // 此用户没有注册
          toast.warn(hasUser.message || '该用户未注册');
        }
      };

      if(actionName === "register"){ // 当前用户准备去注册
          const hasUser = await loginServer.findUserByuserName({username: userName});
          if(hasUser.code === 200){  // 有此用户，不能注册
            toast.warn("此用户已注册，请登录")
          } else { // 可以去注册，该用户未注册
             const addRes = await loginServer.createUser({username: userName, password, captcha: captch, email: formData.email});
             if(addRes.code === 200){ // 新增成功
                toast.success("新增成功，请登录！")
             } else {
               toast.warn(addRes.message)
             }
          }
      }
  
    } catch (error) {
      console.log(error)
    }
  })


  // 获取验证码
  const queryCatch = async () => {
    try {
      const res = await loginServer.queryCaptcha();
      setCaptchSvg(res.captcha)
    } catch (error) {
      console.log(error)
    }
  }

  useEffect(() => {
    queryCatch()
  }, [refreshSvg])

  const [actionName, setActionName] = useState<'login' | 'register'>('login'); //login: 登录  register： 注册
  const actionTypes = [
    {
      value:'login',
      label:"登录"
    },
    {
      value:'register',
      label:"注册"
    }
  ];
  const handleRadioChange = (evt:any) => {
    const r = evt.target.value
    setActionName(r)
  }

  return(<div className={`${styles["login-component"]} ${className}`}>
     <ToastContainer />
    <div className={`${styles["login-header"]}`}>
      <div className={`${styles["header-title"]}`}>{title}</div>
      {!onlySubmit && <div className={`${styles["header-close"]}`} onClick={onClose}><span className="fa fa-solid fa-close"></span></div>}
    </div>
     <form onSubmit={onSubmit} className={`${styles["login-form"]}`}>
     <FormItem
            label="操作类型"
            name="actionType"
            customFormItemValue={`${styles['customFormActionItemValue']}`}
            errors={errors}
          >
            <div className={`${styles["role-form"]}`}>
              {
                actionTypes.map((r, i) => <div key={i} className={`${styles['role-item']}`}><input checked={actionName === r.value} type="radio" id={r.value} value={r.value} {...register("actionType", {required:'请选择操作类型'})}  onChange={handleRadioChange} /> <label htmlFor={r.value}>{r.label}</label></div>)
              }
            </div>
          </FormItem>
    
        <FormItem 
            label="登录名"
            name="userName"
            className={`${styles["custom-base-item"]}`}
            errors={errors}>
            <input
                className={`${styles["base-input"]}`}
                id="userName"
                placeholder="请输入登录名"
                {...register("userName", {
                  required: "请输入登录名",
                  pattern: {
                    value: /^[^\u4e00-\u9fa5]{1,}$/, // 这个正则是匹配除中文外任何字符
                    message:"登录名不能用中文"
                  }
                })}
            />
        </FormItem>
        <FormItem 
            label="密码"
            name="password"
            className={`${styles["custom-base-item"]}`}
            errors={errors}>
            <input
                className={`${styles["base-input"]}`}
                id="password"
                placeholder="请输入密码"
                {...register("password", {
                  required: "请输入密码",
                  pattern: {
                    value: /^[^\u4e00-\u9fa5]{1,}$/, // 这个正则是匹配除中文外任何字符
                    message:"密码不允许中文"
                  }
                })}
            />
        </FormItem>
        {
          actionName === "register" &&  <FormItem 
          label="邮箱"
          name="email"
          className={`${styles["custom-base-item"]}`}
          errors={errors}>
          <input
              className={`${styles["base-input"]}`}
              id="email"
              placeholder="请输入邮箱"
              {...register("email", {
                required: "请输入邮箱",
                pattern: {
                  value: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, // 这个正则是匹配除中文外任何字符
                  message:"请输入正确的邮箱"
                }
              })}
          />
      </FormItem>
        }
       
        <FormItem 
          label="验证码"
          name="captch"
          className={`${styles["custom-base-item"]} ${styles["custom-base-item-value"]} `}
          customFormItemValue={`${styles['customFormItemValue']}`}
          errors={errors}
        >
            <div className={`${styles["captch"]}`}>
              <input className={`${styles["base-input"]} ${styles["captchInput"]}`} type="text"  {...register('captch', {required:'请输入验证码'})} placeholder="验证码"/>
              {/* <Image  src={captchSvg} alt="user pic" width={100} height={35} />  */}
              <span className={`${styles["captchImage"]}`} dangerouslySetInnerHTML={{ __html : captchSvg }} onClick={newChangeCaptch}></span>
            </div>
        </FormItem>


        <div className={`${styles["submit-foolter"]}`}>
           {!onlySubmit && <span className={`${styles["onSubmit-oncancel"]}`} onClick={onClose}>取消</span>} 
            <button type="submit" className={`${styles["onSubmit-btn"]}`}>提交</button>
          </div>
      </form>

  </div>)
}


export default Login;